package com.company.www;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/*
以products.xml作为基础，实现客户购买的方法，
输入商品号和购买数量，计算应付金额，
如果是折扣商品，打七折；如果购买数量超过库存量，
给出提示库存不足，如果购买成功，扣除相应的数量。
 */

public class HomeWork5 {
	static List<Product> products = new ArrayList<>();
	
	public static void buy(String productId, int num) {
		
		for (Product P : products) {
			if (P.getProductno().equals(productId)) {
				if (P.getStockcount() >= num) {
					System.out.println(P.getPrice() * num + "元");
				} else {
					System.out.println("库存不足！！");
					return;
				}
			}
		}
		
	}
	
	public static void main(String[] args) {
		SAXReader saxReader = new SAXReader();
		Document document = null;
		try {
			document = saxReader.read(new File("src/products.xml"));
			Element rootEle = document.getRootElement();//得到根元素
			List<Element> productList = rootEle.elements("product");
			for (Element product : productList) {
				String id = product.attributeValue("id");
				String manufacturer = product.elementTextTrim("manufacturer");
				String productno = product.elementTextTrim("productno");
				String name = product.elementTextTrim("name");
				String price = product.elementTextTrim("price");
				String stockcount = product.elementTextTrim("stockcount");
				//创建一个产品的对象
				Product product2 = new Product();
				product2.setId(Integer.valueOf(id));
				product2.setManufacturer(manufacturer);
				product2.setName(name);
				product2.setPrice(Double.valueOf(price));
				product2.setStockcount(Integer.valueOf(stockcount));
				product2.setProductno(productno);
				//放入List集合中
				products.add(product2);
			}
			Scanner input = new Scanner(System.in);
			System.out.println("请输入您的购买数量：");
			int num = input.nextInt();
			System.out.println("请输入您的购买商品编号：");
			String numId = input.next();
			buy(numId, num);
			
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}
